/**
 * @author xiufu.wang
 */
import BaseRequestActuator from './BaseRequestActuator'
import {isStandardBrowserEnv} from 'axios/lib/utils'

const filenameRegex =  /(filename|fileName)[^;=\n]*=(.+)?/
export default class GetRequestActuator extends BaseRequestActuator {
  constructor(config) {
    //默认get
    super(config, 'get', 'params')
  }

  get(){
    this.dataField = 'params'
    this.method = 'get'
    return this
  }
  //应用于下载
  windowOpen(){
    this.userConfig.windowOpen = true
    return this
  }

  post(){
    this.method = 'post'
    this.dataField = 'data'
    return this
  }

  getFileName(header){
    const unknown = '未知附件名称'
    const h = Object.keys(header || {}).filter(r => r.toLowerCase() === 'content-disposition')
    if (h.length < 1 && !header[h[0]]){
        return unknown
    }
    var disposition = decodeURI(header[h[0]])
    if (disposition && disposition.indexOf('attachment') !== -1) {
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[2]) {
            return matches[2].replace(/['"]/g, '');
        }
    }
    return unknown
  }

  async done(url, data) {
    
    this.responseType('blob')
    const {response, err} = await super.done(url, data)
    if(this.userConfig.windowOpen && this.method.toLocaleLowerCase() === 'get'){
      return {response, err}
    }
    if (isStandardBrowserEnv() && !err){
        let fileName;
        if (response.headers['save-as-name']) {
          fileName = decodeURIComponent(response.headers['save-as-name']);
        } else {
          fileName = this.getFileName(response.headers);
        }
        // IE
        if (window.navigator.msSaveOrOpenBlob){
            window.navigator.msSaveOrOpenBlob(response.data, fileName)
        } else {
            let url = window.URL.createObjectURL(response.data);
            let a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            // a.download = this.getFileName(response.headers);
            if (response.headers['save-as-name']) {
              a.download = decodeURIComponent(response.headers['save-as-name']);
            } else {
              a.download = this.getFileName(response.headers);
            }
            a.click();
            window.URL.revokeObjectURL(url);
        }
    }
    return {response, err}
  }
}